<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  medias
 */

class m_medias_actions_block_AddEmbededMediaAction extends m_backoffice_extends_FormModal
{
	public function execute()
	{
		$folder = $this->getDocumentFromRequest();
        $this->setModalParameters();

        if($this->isFormSubmit())
        {
            $values = $this->getFormValues('form');
            $mediaUrl = f_utils_AutoEmbed::getInstance();
            $errors = array();

            if(empty($values['title']))
            {
                $errors['title'] = $this->getLocale('medias.forms.required');
            }

            if($mediaUrl->parseUrl($values['link']) && empty($errors))
            {
                if($folder instanceof m_backoffice_documents_Folder)
                {
                    $media = m_medias_documents_Media::createNew();
                    $media	->setMime("link/".strtolower(str_replace(" ", "-", $mediaUrl->getStub('title'))))
                            ->setAuthor("pagizer")
                            ->setExt($mediaUrl->getStub('title'))
                            ->setLabel($values['link'])
                            ->setTitle($values['title'])
                            ->save(false);

                    $folder->addMedia($media)->save(false);
                }
                
                $this->closeModalAndRefresh();
            }
            else
            {
                $errors['link'] = $this->getLocale('medias.forms.linkError');
            }

            $this->addToModel('errors', $errors);
        }

        $this->setView('success');
	}	
	
	public function validate()
	{
		return $this->getUserContext()->hasRight(array("backoffice_accessBo", "medias_Add"));
	}
	
	public function errorHandler()
	{
		return null;
	}
}